package com.geh.learn.thread;

/**
 * wait()方法与notify()必须要与synchronized(resource)一起使用
 * <p>
 * Created by gehui on 2017/2/23.
 */
public class WaitNotify {
    public static void main(String args[]) {
        // 以该对象为共享资源
        final byte a[] = {0};
        new Thread(new NumberPrint(1, a), "one").start();
        new Thread(new NumberPrint(2, a), "two").start();
    }
}

class NumberPrint implements Runnable {
    private int number;
    public byte res[];
    public static int count = 6;

    public NumberPrint(int number, byte a[]) {
        this.number = number;
        res = a;
    }

    public void run() {
        synchronized (res) {
            while (count-- > 0) {
                try {
                    // 唤醒等待res资源的线程，把锁交给线程（该同步锁执行完毕自动释放锁）
                    res.notify();
                    System.out.println("number : " + number);
                    // 释放CPU控制权，释放res的锁，本线程阻塞，等待被唤醒
                    res.wait();
                    System.out.println("------线程 " + Thread.currentThread().getName() + " 获得锁，wait()后的代码继续运行：" + number);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return;
        }
    }
}
